﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;
using Peninsula.Common;
using Peninsula.Utility.Extensions;

namespace Peninsula.Cache
{
    public class MvcSiteCache : ISiteCache
    {
        /// <summary>
        /// 获取/设置缓存
        /// </summary>
        /// <typeparam name="T">要缓存的数据的类型</typeparam>
        /// <param name="key"></param>
        /// <param name="getter">获取要缓存的数据的委托</param>
        /// <param name="slidbing">缓存时间</param>
        /// <param name="updateExpiredTime">是否需要延长时间</param>
        /// <param name="refresh">强制使用新数据</param>
        /// <returns>缓存的数据</returns>
        public T Get<T>(string key, Func<T> getter, TimeSpan slidbing = default(TimeSpan), bool updateExpiredTime = false, bool refresh = false) where T : class
        {
            T value = HttpContext.Current.Cache.Get(key) as T;

            if (slidbing == default(TimeSpan))
            {
                slidbing = DateTime.Now.AddHours(1) - DateTime.Now;
            }

            bool newValue = false;
            //如果缓存里没有，或者需要刷新，重新设置
            if (value.IsNull() || refresh)
            {
                value = getter.Invoke();
                newValue = true;
            }

            //如果缓存里有，重新设置
            if (newValue || updateExpiredTime)
            {
                HttpContext.Current.Cache.Remove(key);
                HttpContext.Current.Cache.Add(key, value, null, DateTime.Now.Add(slidbing), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
            }

            return value;
        }

        public void Set<T>(string key, T value, TimeSpan slidbing = default(TimeSpan)) where T : class
        {
            HttpContext.Current.Cache.Remove(key);
            HttpContext.Current.Cache.Add(key, value, null, DateTime.Now.Add(slidbing), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
        }


        public bool TryGet<T>(string key, out T value) where T : class
        {
            try
            {
                value = value = HttpContext.Current.Cache.Get(key) as T;
                return true;
            }
            catch
            {
            }
            value = default(T);
            return false;
        }

        public void Remove(string key)
        {
            HttpContext.Current.Cache.Remove(key);
        }
    }
}
